﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using OnlineVideos.Data;
using Common.Library;
using System.Threading.Tasks;
using OnlineVideos.Entities;

namespace OnlineVideos.Views
{
    public partial class UserBrowserPage : PhoneApplicationPage
    {
        public List<string> NavigationHistory = new List<string>();
        public UserBrowserPage()
        {
            InitializeComponent();
            Loaded += UserBrowserPage_Loaded;
        }

        void UserBrowserPage_Loaded(object sender, RoutedEventArgs e)
        {
            
            string url = Task.Run(async()=>await Constants.connection.Table<WebInformation>().Where(i => i.ShowID == AppSettings.ShowUniqueID).FirstOrDefaultAsync()).Result.NavigationUri;
            webBrowser1.Navigate(new Uri(url, UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
        }

      
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (NavigationHistory.Count > 0)
            {
                e.Cancel = true;
                NavigateBack();
            }
            else
                base.OnBackKeyPress(e);
        }

        public void NavigateBack()
        {
            webBrowser1.InvokeScript("eval", "history.go(-1)");
            NavigationHistory.RemoveAt(NavigationHistory.Count - 1);
        }

        private void webBrowser1_LoadCompleted_1(object sender, NavigationEventArgs e)
        {
            webBrowser1.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(webBrowser1_Navigated);
        }
        void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            NavigationHistory.Add(e.Uri.ToString());

        }
    }
}